package com.xca.rxjavademo.presenter;

import android.content.Context;
import android.util.Log;

import com.xca.rxjavademo.contract.NewsContact;
import com.xca.rxjavademo.entity.WorldNews;
import com.xca.rxjavademo.service.NewsService;

import org.jetbrains.annotations.NotNull;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewsPresenter implements NewsContact.NewsPresenter{
    private NewsContact.NewsView mMainView;
    private Context mContext;
    public NewsPresenter(NewsContact.NewsView mMainView , Context mContext)
    {
        this.mMainView = mMainView;
        this.mContext = mContext;
    }
    @Override
    public void getData() {
        String url = "https://api.oioweb.cn/api/" ;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
        NewsService service = retrofit.create(NewsService.class);
        service.getData()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<WorldNews>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull WorldNews worldNews) {
                        if (mMainView != null){
                            mMainView.showData(worldNews);
                        } else {
                            Log.e("空指针警告", "mMainView 为 null");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("错误处理", "数据获取失败: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
